from typing import Optional, List
from sqlalchemy.orm import Session
from datetime import datetime
import uuid

from app.core.security import get_password_hash, verify_password
from app.models.user import User, UserFavorite, UserHistory
from app.schemas.user import UserCreate

def get_user(db: Session, user_id: str) -> Optional[User]:
    return db.query(User).filter(User.id == user_id).first()

def get_user_by_email(db: Session, email: str) -> Optional[User]:
    return db.query(User).filter(User.email == email).first()

def create_user(db: Session, user_in: UserCreate) -> User:
    try:
        db_user = User(
            id=str(uuid.uuid4()),
            email=user_in.email,
            nickname=user_in.nickname or user_in.email.split('@')[0],
            hashed_password=get_password_hash(user_in.password),
            is_active=True,
            create_time=datetime.utcnow(),
            last_login_time=datetime.utcnow()
        )
        db.add(db_user)
        db.commit()
        db.refresh(db_user)
        return db_user
    except Exception as e:
        db.rollback()
        print(f"创建用户失败: {e}")  # 添加错误日志
        raise

def authenticate_user(db: Session, email: str, password: str) -> Optional[User]:
    user = get_user_by_email(db, email=email)
    if not user:
        return None
    if not verify_password(password, user.hashed_password):
        return None
    return user

def update_user(db: Session, user_id: str, **kwargs) -> Optional[User]:
    try:
        db_user = get_user(db, user_id)
        if not db_user:
            return None
        
        for key, value in kwargs.items():
            setattr(db_user, key, value)
        
        db.commit()
        db.refresh(db_user)
        return db_user
    except Exception as e:
        db.rollback()
        print(f"更新用户失败: {e}")  # 添加错误日志
        raise

def update_password(db: Session, user_id: str, new_password: str) -> Optional[User]:
    return update_user(
        db,
        user_id,
        hashed_password=get_password_hash(new_password)
    )

def update_last_login(db: Session, user_id: str) -> Optional[User]:
    return update_user(
        db,
        user_id,
        last_login_time=datetime.utcnow()
    )

# 收藏相关操作
def get_user_favorites(
    db: Session,
    user_id: str,
    skip: int = 0,
    limit: int = 20
) -> tuple[List[UserFavorite], int]:
    query = db.query(UserFavorite).filter(UserFavorite.user_id == user_id)
    total = query.count()
    items = query.offset(skip).limit(limit).all()
    return items, total

def add_favorite(db: Session, user_id: str, node_id: str) -> UserFavorite:
    try:
        db_favorite = UserFavorite(
            id=str(uuid.uuid4()),
            user_id=user_id,
            node_id=node_id
        )
        db.add(db_favorite)
        db.commit()
        db.refresh(db_favorite)
        return db_favorite
    except Exception as e:
        db.rollback()
        print(f"添加收藏失败: {e}")  # 添加错误日志
        raise

def remove_favorite(db: Session, user_id: str, node_id: str) -> bool:
    try:
        result = db.query(UserFavorite).filter(
            UserFavorite.user_id == user_id,
            UserFavorite.node_id == node_id
        ).delete()
        db.commit()
        return result > 0
    except Exception as e:
        db.rollback()
        print(f"删除收藏失败: {e}")  # 添加错误日志
        raise

# 浏览历史相关操作
def get_user_history(
    db: Session,
    user_id: str,
    skip: int = 0,
    limit: int = 20
) -> tuple[List[UserHistory], int]:
    query = db.query(UserHistory).filter(UserHistory.user_id == user_id)
    total = query.count()
    items = query.offset(skip).limit(limit).all()
    return items, total

def add_history(db: Session, user_id: str, node_id: str) -> UserHistory:
    try:
        db_history = UserHistory(
            id=str(uuid.uuid4()),
            user_id=user_id,
            node_id=node_id
        )
        db.add(db_history)
        db.commit()
        db.refresh(db_history)
        return db_history
    except Exception as e:
        db.rollback()
        print(f"添加历史记录失败: {e}")  # 添加错误日志
        raise

def clear_history(db: Session, user_id: str) -> bool:
    try:
        result = db.query(UserHistory).filter(
            UserHistory.user_id == user_id
        ).delete()
        db.commit()
        return result > 0
    except Exception as e:
        db.rollback()
        print(f"清除历史记录失败: {e}")  # 添加错误日志
        raise 